﻿using famails.bus;
using famails.common;
using famails.dto;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace famails.BackEnd.page
{
    public partial class ClientDetail : System.Web.UI.Page
    {

        ClientBUS clientbus;
        ClientRegisterBUS clientRegister;
        ClientFunctionBUS clientFunction;
        PackageBUS pkgBus;
        PackageLimitBUS pkglimitBus;
        FunctionBUS function;
        UserLoginDTO userLogin = null;
        string imagePath = "images/clientlogo";
        protected void Page_Load(object sender, EventArgs e)
        {
            userLogin = getUserLogin();
            if (!IsPostBack)
            {
                LoadData();
                Page.Header.Title = "Thông tin tài khoản!!!";
            }
        }
        private UserLoginDTO getUserLogin()
        {
            if (Session["us-login"] != null)
            {
                return (UserLoginDTO)Session["us-login"];
            }
            else Response.Redirect("~");//test confict
            return null;
        }
        private void LoadData()
        {
            try
            {
                #region LoadData
                if (userLogin.UserId > 0)
                {
                    //int user = Convert.ToInt32(Request.QueryString["user"].ToString());
                    int user = userLogin.UserId;
                    clientbus = new ClientBUS();
                    DataTable dtClient = new DataTable();
                    dtClient = clientbus.GetByID(user);
                    string email = dtClient.Rows[0]["email"] + "";
                    int registerId = Convert.ToInt32(dtClient.Rows[0]["registerId"].ToString());
                    int clientId = Convert.ToInt32(dtClient.Rows[0]["clientId"].ToString());
                    clientRegister = new ClientRegisterBUS();
                    DataTable dtClientRegister = new DataTable();
                    dtClientRegister = clientRegister.GetbyID(registerId);
                    string packageid = dtClientRegister.Rows[0]["packageId"].ToString();
                    DataTable dtpackage = new DataTable();
                    pkgBus = new PackageBUS();
                    dtpackage = pkgBus.GetById(Convert.ToInt32(packageid));
                    int packagelimitid = Convert.ToInt32(dtClientRegister.Rows[0]["limitid"].ToString());
                    DataTable dtlimit = new DataTable();
                    pkglimitBus = new PackageLimitBUS();
                    dtlimit = pkglimitBus.GetByUserIdPackageLimit(packagelimitid);
                    string SoluongEmail = "";
                    if (dtpackage.Rows.Count > 0)
                    {
                        lblTenGoi.Text = dtpackage.Rows[0]["packageName"].ToString();
                        SoluongEmail = dtpackage.Rows[0]["isUnlimit"].ToString();
                        if (SoluongEmail.Trim() != "True")
                        {
                            SoluongEmail = dtpackage.Rows[0]["emailCount"].ToString();
                            lblSoLuongEmail.Text = SoluongEmail;
                        }
                        else
                        {
                            lblSoLuongEmail.Text = "Không giới hạn";
                        }
                    }
                    lblNgayKichHoat.Text = Convert.ToDateTime(dtClient.Rows[0]["activeDate"]).ToString("dd/MM/yyyy");
                    lblNgayDenHan.Text = Convert.ToDateTime(dtClient.Rows[0]["expireDate"]).ToString("dd/MM/yyyy");
                    if (Convert.ToDateTime(dtClient.Rows[0]["expireDate"]) < DateTime.Now)
                        lblNgayDenHan.Text = Convert.ToDateTime(dtClient.Rows[0]["expireDate"]).ToString("dd/MM/yyyy'(<label style=\"color:red\">Đã hết hạn)</label>'");
                    lblSoTaiKhoanCon.Text = dtClientRegister.Rows[0]["subAccontCount"].ToString();

                    string GioihanEmail = dtlimit.Rows[0]["isUnlimit"].ToString();
                    if (GioihanEmail.Trim() != "True")
                    {
                        GioihanEmail = dtlimit.Rows[0]["under"].ToString();
                        lblGioiHanEmail.Text = Convert.ToDecimal(GioihanEmail).ToString("#,###");
                    }
                    else
                    {
                        lblGioiHanEmail.Text = "Không giới hạn";
                    }
                    clientFunction = new ClientFunctionBUS();
                    DataTable dtfunction = new DataTable();
                    dtfunction = clientFunction.GetByregisterIdandclientId(registerId, clientId);
                    if (dtfunction != null && dtfunction.Rows.Count > 0)
                    {
                        DataTable dtTemp = new DataTable();
                        dtTemp.Columns.Add("functionName", typeof(String));
                        foreach (DataRow drfunction in dtfunction.Rows)
                        {
                            DataRow dr = dtTemp.NewRow();
                            function = new FunctionBUS();
                            string idFunction = drfunction["functionId"].ToString();
                            DataTable dtTemp2 = function.GetByFunctionId(Convert.ToInt32(idFunction));
                            if (dtTemp2 != null && dtTemp2.Rows.Count > 0)
                            {
                                string FunctionName = dtTemp2.Rows[0]["functionName"].ToString();
                                dr["functionName"] = FunctionName;
                                dtTemp.Rows.Add(dr);
                            }
                        }

                        rptFunction.DataSource = dtTemp;
                        rptFunction.DataBind();
                    }
                    txtHoTen.Text = dtClient.Rows[0]["clientName"].ToString();
                    txtDiaChi.Text = dtClient.Rows[0]["address"].ToString();
                    txtSoDienThoai.Text = dtClient.Rows[0]["phone"].ToString();
                    DateTime d = DateTime.Now;// Convert.ToDateTime(dtClient.Rows[0]["dateofbirth"].ToString());
                    if (DateTime.TryParse(dtClient.Rows[0]["dateofbirth"] + "", out d))
                        txtBirthday_v.Value = d.ToString("yyyy/MM/dd");
                    lblEmail.Text = email;

                    txtCompany.Text = dtClient.Rows[0]["CompanyName"] + "";
                    txtphone_company.Text = dtClient.Rows[0]["CompanyPhone"] + "";
                    txtaddress_company.Text = dtClient.Rows[0]["CompanyAddress"] + "";
                    txtfax_company.Text = dtClient.Rows[0]["CompanyFax"] + "";
                    txtemail_company.Text = dtClient.Rows[0]["CompanyEmail"] + "";
                    imgLogo.ImageUrl = dtClient.Rows[0]["CompanyLogo"] + "" == "" ? "http://placehold.it/250x80" : "../../" + dtClient.Rows[0]["CompanyLogo"] + "";
                    hdfImage.Value = dtClient.Rows[0]["CompanyLogo"] + "";

                    DateTime today = DateTime.Now.Date;

                    DateTime dateexpire = DateTime.Now;

                    if (DateTime.TryParse(dtClient.Rows[0]["expireDate"] + "", out dateexpire) && dateexpire < today)
                    {
                        btnGiahan.Enabled = true;
                        btnGiahan.Text = "(Đã hết hạn " + (today - dateexpire).TotalDays + " ngày)";
                    }
                    else
                    {
                        btnGiahan.Enabled = false; ;
                        btnGiahan.CssClass = "button round image-right ic-add text-upper";
                        btnGiahan.Text = "(Còn lại " + (dateexpire - today).TotalDays + " ngày)";
                    }
                }
                else
                {

                }
                #endregion
            }
            catch (Exception ex)
            {
                common.Common.logs(userLogin.Username + " - ClientDetail - LoadData", ex, Common.logType.error);
                pnError.Visible = true;
                lblError.Text = "Có lỗi trong quá trình nạp dữ liệu!" + ex.Message.ToString();
            }
        }
        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                if (CheckBeforeSave())
                {
                    return;
                }
                else
                {
                    clientbus = new ClientBUS();
                    ClientDTO dto = new ClientDTO();
                    dto.ClientId = userLogin.ClientID;
                    dto.ClientName = txtHoTen.Text;
                    dto.Address = txtDiaChi.Text;
                    dto.Phone = txtSoDienThoai.Text;
                    dto.CompanyName = txtCompany.Text;
                    dto.CompanyPhone = txtphone_company.Text;
                    dto.CompanyAddress = txtaddress_company.Text;
                    dto.CompanyFax = txtfax_company.Text;
                    dto.CompanyEmail = txtemail_company.Text;
                    dto.CompanyLogo = SaveFile();
                    DateTime? dateofbirth = convertStringToDate(txtBirthday_v.Value);
                    dto.DayOfBirth = dateofbirth.Value;
                    clientbus.UpdateInfomation(dto);
                    LoadData();
                    pnSuccess.Visible = true;
                    lblSuccess.Text = "Cập nhật thông tin thành công!";
                }
            }
            catch (Exception ex)
            {
                common.Common.logs(userLogin.Username + "-ClientDetail - btnUpdate_Click", ex, Common.logType.error);
                pnError.Visible = true;
                lblError.Text = "Lưu dữ liệu không thành công!" + ex.Message.ToString();
            }
        }
        bool CheckBeforeSave()
        {
            string message = "";
            if (txtHoTen.Text.Trim() == "")
                message = "Họ tên không được rỗng!";
            if (txtDiaChi.Text.Trim() == "")
                message = "Địa chỉ không được rỗng!";
            if (txtSoDienThoai.Text.Trim() == "")
                message = "Số điện thoại không được rỗng!";
            if (convertStringToDate(txtBirthday_v.Value) == null)
                lblError.Text = "Ngày sinh không hợp lệ!";
            if (message.Length > 0)
            {
                pnError.Visible = true;
                lblError.Text = message;
            }
            return message.Length > 0;
        }

        private string SaveFile()
        {
            string newFile = Guid.NewGuid() + ".jpg";
            newFile = Path.Combine(imagePath, newFile);
            string filePath = Server.MapPath("../../" + newFile);
            if (file_company.HasFile)
            {
                file_company.SaveAs(filePath);
                return newFile;
            }
            else return hdfImage.Value;
        }
        protected DateTime? convertStringToDate(string strDate)
        {
            try
            {
                int day = int.Parse(strDate.Substring(0, 2));
                int month = int.Parse(strDate.Substring(3, 2));
                int year = int.Parse(strDate.Substring(6, 4));
                DateTime dDate = new DateTime(year, month, day, 00, 00, 00);
                return dDate;
            }
            catch// (Exception ex)
            {
                //logs.Error(userLogin.Username + "-Client - btnAdd_Click", ex);
                //pnError.Visible = true;
                //lblError.Text = "Ngày sinh không hợp lệ!" + ex.Message.ToString();
            }
            return null;
        }
        protected void btnGiahan0_Click(object sender, EventArgs e)
        {
            Response.Redirect("packagechange.aspx?type=editoption");
        }
        protected void btnGiahan_Click(object sender, EventArgs e)
        {
            Response.Redirect("PackageChange.aspx?type=extend");
        }
        protected void btnUpGradeServices_Click(object sender, EventArgs e)
        {
            Response.Redirect("packagechange.aspx?type=upgrade");
        }

        protected void deletefile_Click(object sender, EventArgs e)
        {
            string newFile = hdfImage.Value;
            string filePath = Server.MapPath("../../" + newFile);
            File.Delete(filePath);
        }
    }
}